<template>
  <view class="contest-page" :class="{ 'dark-mode': isDarkMode }">
    <!-- 使用全局导航栏 -->
    <nav-bar @theme-change="onThemeChange"></nav-bar>
    
    <view class="content-wrapper">
      <!-- 标题和搜索区域 -->
      <view class="page-header">
        <view class="header-left">
          <view class="page-title">比赛中心</view>
          <view class="page-subtitle">参加编程比赛，挑战自我，提升实力</view>
        </view>
        <view class="search-box">
          <input type="text" class="search-input" placeholder="搜索比赛..." v-model="searchKeyword" @input="filterContests" />
          <button class="search-btn">搜索</button>
        </view>
      </view>
      
      <!-- 过滤器 -->
      <view class="filter-container">
        <view class="filter-section">
          <view class="filter-title">比赛状态</view>
          <view class="filter-options">
            <view 
              v-for="(status, index) in statusOptions" 
              :key="index"
              class="filter-option"
              :class="{ active: selectedStatus === status.value }"
              @click="setStatus(status.value)"
            >
              {{ status.label }}
            </view>
          </view>
        </view>
        
        <view class="filter-section">
          <view class="filter-title">比赛类型</view>
          <view class="filter-options">
            <view 
              v-for="(type, index) in typeOptions" 
              :key="index"
              class="filter-option"
              :class="{ active: selectedTypes.includes(type.value) }"
              @click="toggleType(type.value)"
            >
              {{ type.label }}
            </view>
          </view>
        </view>
      </view>
      
      <!-- 比赛列表 -->
      <view class="contests-container">
        <view v-if="filteredContests.length === 0" class="empty-tip">
          没有找到符合条件的比赛
        </view>
        
        <view 
          v-for="(contest, index) in filteredContests" 
          :key="index"
          class="contest-card"
          @click="navigateToContest(contest.id)"
        >
          <view class="contest-status" :class="contest.status">
            {{ getStatusText(contest.status) }}
          </view>
          
          <view class="contest-header">
            <view class="contest-title">{{ contest.title }}</view>
          </view>
          
          <view class="contest-info">
            <view class="info-item">
              <text class="icon">🕒</text>
              <text>开始时间: {{ formatDate(contest.startTime) }}</text>
            </view>
            <view class="info-item">
              <text class="icon">⏱️</text>
              <text>持续时间: {{ formatDuration(contest.duration) }}</text>
            </view>
            <view class="info-item">
              <text class="icon">📝</text>
              <text>题目数量: {{ contest.problemCount }}</text>
            </view>
            <view class="info-item">
              <text class="icon">👥</text>
              <text>已报名: {{ contest.registeredCount }}人</text>
            </view>
            <view class="info-item">
              <text class="icon">🏆</text>
              <text>赛制: {{ getFormatText(contest.format) }}</text>
            </view>
          </view>
          
          <view class="contest-footer">
            <view class="tags">
              <view v-for="(tag, tagIndex) in contest.tags" :key="tagIndex" class="tag">
                {{ tag }}
              </view>
            </view>
          </view>
          
          <!-- 移动按钮到右下角 -->
          <button 
            class="register-btn" 
            v-if="contest.status !== 'ended'" 
            @click.stop="registerContest(contest.id)"
            :class="{ 'enter-btn': contest.status === 'ongoing' }"
          >
            {{ contest.status === 'upcoming' ? '报名参加' : '立即进入' }}
          </button>
        </view>
      </view>
      
      <!-- 分页 -->
      <view class="pagination">
        <text 
          class="page-btn" 
          :class="{ disabled: currentPage === 1 }"
          @click="changePage(currentPage - 1)"
        >上一页</text>
        
        <text 
          v-for="page in displayedPages" 
          :key="page"
          class="page-number"
          :class="{ active: currentPage === page }"
          @click="changePage(page)"
        >{{ page }}</text>
        
        <text 
          class="page-btn" 
          :class="{ disabled: currentPage === totalPages }"
          @click="changePage(currentPage + 1)"
        >下一页</text>
      </view>
    </view>
  </view>
</template>

<script>
import NavBar from '@/components/NavBar.vue';
import { getThemeMode } from '@/utils/themeManager.js';

export default {
  components: {
    NavBar
  },
  
  data() {
    return {
      isDarkMode: false,
      contests: [],
      searchKeyword: '',
      selectedStatus: 'all',
      selectedTypes: [],
      currentPage: 1,
      pageSize: 5,
      
      // 筛选选项
      statusOptions: [
        { label: '全部', value: 'all' },
        { label: '即将开始', value: 'upcoming' },
        { label: '进行中', value: 'ongoing' },
        { label: '已结束', value: 'ended' }
      ],
      typeOptions: [
        { label: '周赛', value: 'weekly' },
        { label: '月赛', value: 'monthly' },
        { label: '编程马拉松', value: 'marathon' },
        { label: '团队赛', value: 'team' },
        { label: '模拟赛', value: 'simulation' }
      ]
    };
  },
  
  computed: {
    // 过滤后的比赛列表
    filteredContests() {
      let result = this.contests;
      
      // 搜索关键词过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        result = result.filter(contest => 
          contest.title.toLowerCase().includes(keyword) || 
          contest.tags.some(tag => tag.toLowerCase().includes(keyword))
        );
      }
      
      // 状态过滤
      if (this.selectedStatus !== 'all') {
        result = result.filter(contest => contest.status === this.selectedStatus);
      }
      
      // 类型过滤
      if (this.selectedTypes.length > 0) {
        result = result.filter(contest => 
          this.selectedTypes.includes(contest.type.toLowerCase())
        );
      }
      
      // 返回当前页的数据
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return result.slice(start, end);
    },
    
    // 总页数
    totalPages() {
      return Math.ceil(this.getFilteredTotal() / this.pageSize);
    },
    
    // 显示的页码
    displayedPages() {
      const pages = [];
      const maxPages = 5; // 最多显示5个页码
      
      if (this.totalPages <= maxPages) {
        // 如果总页数小于等于最大显示页数，则全部显示
        for (let i = 1; i <= this.totalPages; i++) {
          pages.push(i);
        }
      } else {
        // 否则智能显示当前页附近的页码
        let startPage = Math.max(1, this.currentPage - 2);
        let endPage = Math.min(this.totalPages, startPage + maxPages - 1);
        
        // 调整起始页，确保显示maxPages个页码
        if (endPage - startPage + 1 < maxPages) {
          startPage = Math.max(1, endPage - maxPages + 1);
        }
        
        for (let i = startPage; i <= endPage; i++) {
          pages.push(i);
        }
      }
      
      return pages;
    }
  },
  
  onLoad() {
    // 检查当前主题
    this.isDarkMode = getThemeMode();
    
    // 监听全局主题变更
    uni.$on('global-theme-changed', (isDark) => {
      this.isDarkMode = isDark;
    });
    
    // 加载比赛数据
    this.loadContests();
  },
  
  onShow() {
    // 通知导航栏当前页面
    const currentPath = '/' + this.getPageRoute();
    uni.$emit('page-changed', currentPath);
  },
  
  onUnload() {
    uni.$off('global-theme-changed');
  },
  
  methods: {
    onThemeChange(isDark) {
      this.isDarkMode = isDark;
    },
    
    // 加载比赛数据
    loadContests() {
      // 生成模拟数据
      const now = new Date();
      const contestTypes = ['周赛', '月赛', '编程马拉松', '团队赛', '模拟赛'];
      const tagsList = [
        ['算法', '数据结构', '动态规划'],
        ['贪心', '图论', '模拟'],
        ['分治', '搜索', '树'],
        ['字符串', '哈希', '排序'],
        ['数学', '几何', '组合']
      ];
      
      // 生成30个模拟比赛
      this.contests = Array.from({ length: 30 }, (_, i) => {
        // 随机比赛开始时间
        const startOffset = (Math.random() * 20 - 10) * 24 * 60 * 60 * 1000; // -10天到+10天
        const startTime = new Date(now.getTime() + startOffset);
        
        // 随机持续时间（2小时到5小时）
        const duration = (Math.random() * 3 + 2) * 60;
        
        // 计算结束时间
        const endTime = new Date(startTime.getTime() + duration * 60 * 1000);
        
        // 确定比赛状态
        let status;
        if (now < startTime) {
          status = 'upcoming';
        } else if (now > endTime) {
          status = 'ended';
        } else {
          status = 'ongoing';
        }
        
        // 随机选择比赛类型和标签
        const typeIndex = Math.floor(Math.random() * contestTypes.length);
        const type = contestTypes[typeIndex];
        const tags = tagsList[Math.floor(Math.random() * tagsList.length)];
        
        return {
          id: 1000 + i,
          title: `${type} #${Math.floor(Math.random() * 100)}`,
          startTime: startTime,
          duration: duration, // 分钟
          problemCount: Math.floor(Math.random() * 10) + 3, // 3-12道题
          registeredCount: Math.floor(Math.random() * 500) + 50, // 50-550人
          type: type,
          tags: tags,
          status: status
        };
      });
      
      // 按开始时间排序
      this.contests.sort((a, b) => {
        // 进行中的排在最前面
        if (a.status === 'ongoing' && b.status !== 'ongoing') return -1;
        if (a.status !== 'ongoing' && b.status === 'ongoing') return 1;
        
        // 然后是即将开始的，按开始时间正序排列
        if (a.status === 'upcoming' && b.status === 'upcoming') {
          return a.startTime - b.startTime;
        }
        
        // 已结束的比赛按开始时间倒序排列
        if (a.status === 'ended' && b.status === 'ended') {
          return b.startTime - a.startTime;
        }
        
        // 即将开始的排在已结束的前面
        if (a.status === 'upcoming' && b.status === 'ended') return -1;
        if (a.status === 'ended' && b.status === 'upcoming') return 1;
        
        return 0;
      });
    },
    
    // 获取过滤后的总数
    getFilteredTotal() {
      let result = this.contests;
      
      // 搜索关键词过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        result = result.filter(contest => 
          contest.title.toLowerCase().includes(keyword) || 
          contest.tags.some(tag => tag.toLowerCase().includes(keyword))
        );
      }
      
      // 状态过滤
      if (this.selectedStatus !== 'all') {
        result = result.filter(contest => contest.status === this.selectedStatus);
      }
      
      // 类型过滤
      if (this.selectedTypes.length > 0) {
        result = result.filter(contest => 
          this.selectedTypes.includes(contest.type.toLowerCase())
        );
      }
      
      return result.length;
    },
    
    // 设置比赛状态过滤
    setStatus(status) {
      this.selectedStatus = status;
      this.currentPage = 1; // 重置到第一页
    },
    
    // 切换比赛类型过滤
    toggleType(type) {
      const index = this.selectedTypes.indexOf(type);
      if (index > -1) {
        this.selectedTypes.splice(index, 1);
      } else {
        this.selectedTypes.push(type);
      }
      this.currentPage = 1; // 重置到第一页
    },
    
    // 更改页码
    changePage(page) {
      if (page < 1 || page > this.totalPages || page === this.currentPage) {
        return;
      }
      this.currentPage = page;
    },
    
    // 跳转到比赛详情页
    navigateToContest(id) {
      uni.navigateTo({
        url: `/pages/contest/detail?id=${id}`
      });
    },
    
    // 格式化日期
    formatDate(date) {
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    // 格式化持续时间
    formatDuration(minutes) {
      const hours = Math.floor(minutes / 60);
      const mins = Math.floor(minutes % 60);
      
      if (hours > 0) {
        return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`;
      }
      return `${mins}分钟`;
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'upcoming': return '即将开始';
        case 'ongoing': return '进行中';
        case 'ended': return '已结束';
        default: return '未知状态';
      }
    },
    
    // 过滤比赛列表
    filterContests() {
      this.currentPage = 1; // 重置到第一页
    },
    
    // 获取当前页面路径
    getPageRoute() {
      const pages = getCurrentPages();
      if (pages.length > 0) {
        return pages[pages.length - 1].route;
      }
      return '';
    },
    
    // 注册比赛方法
    registerContest(contestId) {
      // 阻止事件冒泡，避免触发卡片的点击事件
      event.stopPropagation();
      
      console.log('注册比赛:', contestId);
      uni.showToast({
        title: '报名成功',
        icon: 'success'
      });
      
      // 跳转到比赛详情页
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/contest/detail?id=${contestId}`
        });
      }, 1000);
    },
    
    // 获取赛制名称
    getFormatText(format) {
      if (!format) return '未知';
      
      const formatMap = {
        'icpc': 'ICPC',
        'oi': 'OI',
        'ioi': 'IOI',
        'acm': 'ACM', 
        'standard': '标准赛制'
      };
      return formatMap[format] || format;
    }
  }
};
</script>

<style>
.contest-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 60px; /* 为导航栏留出空间 */
}

.dark-mode.contest-page {
  background-color: #121212;
  color: #e0e0e0;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面标题和搜索区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.header-left {
  margin-bottom: 15px;
}

.page-title {
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.dark-mode .page-title {
  color: #ffffff;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
}

.dark-mode .page-subtitle {
  color: #aaa;
}

/* 搜索框 */
.search-box {
  display: flex;
  width: 100%;
  max-width: 400px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-right: none;
  border-radius: 4px 0 0 4px;
  outline: none;
  font-size: 15px;
  height: 46px;
  box-sizing: border-box;
}

.dark-mode .search-input {
  background-color: #2a2a2a;
  border-color: #444;
  color: #e0e0e0;
  box-shadow: none;
}

.dark-mode .search-input::placeholder {
  color: #888;
}

.search-btn {
  width: 80px;
  background-color: #20C0B8;
  color: white;
  border: none;
  font-size: 15px;
  cursor: pointer;
  height: 46px;
  border-radius: 0 4px 4px 0;
  transition: background-color 0.2s;
}

.search-btn:hover {
  background-color: #1aa8a1;
}

.dark-mode .search-btn {
  background-color: #158782;
}

.dark-mode .search-btn:hover {
  background-color: #106e69;
}

/* 过滤器区域 */
.filter-container {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.dark-mode .filter-container {
  background-color: #1e1e1e;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.filter-section {
  margin-bottom: 15px;
}

.filter-section:last-child {
  margin-bottom: 0;
}

.filter-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #666;
}

.dark-mode .filter-title {
  color: #aaa;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-option {
  padding: 6px 12px;
  border-radius: 20px;
  background-color: #f0f0f0;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.dark-mode .filter-option {
  background-color: #2a2a2a;
  color: #aaa;
}

.filter-option.active {
  background-color: rgba(32, 192, 184, 0.1);
  color: #20C0B8;
  border: 1px solid #20C0B8;
}

.dark-mode .filter-option.active {
  background-color: rgba(32, 192, 184, 0.2);
}

.filter-option:hover:not(.active) {
  background-color: #e8e8e8;
}

.dark-mode .filter-option:hover:not(.active) {
  background-color: #333;
}

/* 比赛列表 */
.contests-container {
  margin-bottom: 20px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #999;
  font-size: 15px;
}

.dark-mode .empty-tip {
  color: #777;
}

.contest-card {
  background-color: white;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
  padding-bottom: 60px; /* 为按钮留出空间 */
}

.dark-mode .contest-card {
  background-color: #1e1e1e;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.contest-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.dark-mode .contest-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.contest-status {
  position: absolute;
  top: 15px;
  right: 15px;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
}

.contest-status.upcoming {
  background-color: #e3f2fd;
  color: #1976d2;
}

.contest-status.ongoing {
  background-color: #fef2e0;
  color: #f4811f;
}

.contest-status.ended {
  background-color: #f5f5f5;
  color: #9e9e9e;
}

.dark-mode .contest-status.upcoming {
  background-color: rgba(25, 118, 210, 0.2);
  color: #64b5f6;
}

.dark-mode .contest-status.ongoing {
  background-color: rgba(244, 129, 31, 0.2);
  color: #ffb74d;
}

.dark-mode .contest-status.ended {
  background-color: rgba(158, 158, 158, 0.2);
  color: #bdbdbd;
}

.contest-header {
  margin-bottom: 15px;
}

.contest-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
  padding-right: 80px; /* 为状态留出空间 */
  color: #333;
}

.dark-mode .contest-title {
  color: #e0e0e0;
}

.contest-format-tag {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 12px;
  background-color: #e6f7f6;
  color: #20C0B8;
  margin-left: 10px;
}

.dark-mode .contest-format-tag {
  background-color: rgba(32, 192, 184, 0.15);
}

.contest-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.dark-mode .info-item {
  color: #bbb;
}

.icon {
  margin-right: 8px;
}

.contest-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag {
  padding: 4px 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.dark-mode .tag {
  background-color: #2a2a2a;
  color: #aaa;
}

/* 调整按钮位置到右下角 */
.register-btn {
  position: absolute;
  bottom: 15px;
  right: 15px;
  min-width: 100px;
  height: 36px;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(32, 192, 184, 0.2);
  transition: all 0.3s;
  border: none;
  background-color: #20C0B8;
  color: white;
}

.dark-mode .register-btn {
  background-color: #18a39c;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.page-btn,
.page-number {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  text-align: center;
  transition: all 0.2s;
}

.page-btn {
  background-color: #f0f0f0;
  color: #666;
  min-width: 70px;
}

.dark-mode .page-btn {
  background-color: #2a2a2a;
  color: #aaa;
}

.page-number {
  background-color: #f9f9f9;
  color: #666;
  min-width: 36px;
}

.dark-mode .page-number {
  background-color: #252525;
  color: #bbb;
}

.page-number.active {
  background-color: #20C0B8;
  color: white;
}

.dark-mode .page-number.active {
  background-color: #158782;
}

.page-btn.disabled,
.page-number.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn:not(.disabled):hover,
.page-number:not(.active):not(.disabled):hover {
  background-color: #e8e8e8;
}

.dark-mode .page-btn:not(.disabled):hover,
.dark-mode .page-number:not(.active):not(.disabled):hover {
  background-color: #333;
}
</style> 